﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WMPLib;

namespace WJDHApp
{
    public partial class productForm : Form
    {
        System.Timers.Timer t;
        public productForm()
        {
            InitializeComponent();
        }

        private void productForm_Load(object sender, EventArgs e)
        {
            txttoken.Text = "5db791473b684beaa284a5577728604e";
            textBox1.Text = "19_1607_4773_0;3936574";
            textBox3.Text = "5";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //启功监控
                if (button1.Text == "启动监控")
                {
                    double m = Convert.ToDouble(textBox3.Text) * 1000;
                    if (t == null)
                    {
                        t = new System.Timers.Timer(m);
                    }
                    button1.Text = "暂停监控";
                    t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
                    t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
                    t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
                }
                else
                {
                    t.Enabled = false;
                    button1.Text = "启动监控";
                }
            }
            catch (Exception ex)
            {
                textBox2.Text = ex.Message;
            }
        }

        int idx = 0;
        int a = 0;
        //bool showdg = false;
        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                a++;
                if (a % 10 == 0)
                {
                    textBox2.Text = "";//清空
                }
                var res = textBox1.Text.Split(';');
                var strvalue = CanBuy(res[0], res[1]);

                if (strvalue == "有货")
                {
                    idx++;
                    Invoke((MethodInvoker)delegate
                    {
                        textBox2.Text = textBox2.Text.Insert(0, strvalue + Environment.NewLine);
                    });
                    if (idx <= 3)
                    {
                        MessageBox.Show("提示", strvalue, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    }
                }
                else
                {
                    Invoke((MethodInvoker)delegate
                    {
                        textBox2.Text = textBox2.Text.Insert(0, strvalue + a.ToString() + Environment.NewLine);
                    });
                }
            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker)delegate
                {
                    textBox2.Text = ex.Message;
                });
            }
        }

        public string CanBuy(string area, string skuid)
        {
            try
            {
                //{"success":true,"resultMessage":"","resultCode":"0000","result":[{"skuId":1127726,"areaId":"19_1607_4773_0","stockStateId":34,"stockStateDesc":"无货","remainNum":-1}],"code":"0","msg":null}

                string jsonp = string.Format("{{\"area\":\"{0}\",\"skuNums\":[{{\"num\":1,\"skuId\":{1}}}]}}", area, skuid);
                var pstr = HttpHelper.HttpPostParams("https://api.9yiwu.com/jdapi-service/storage/query?accessToken=&mChannal=NG_APP", jsonp);
                var json = JObject.Parse(pstr);
                if (json["resultCode"].ToString() == "0000")
                {
                    string m = json["result"][0]["stockStateDesc"].ToString();
                    if (m == "无货")
                    {
                        return "配送区域无货";
                    }
                    else
                    {
                        PlayThread();
                        return "有货";
                    }
                }
                return "无货";
            }
            catch (Exception ex)
            {
                return "程序异常";
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            var res = textBox1.Text.Split(';');
            textBox2.Text = CanBuy(res[0], res[1]);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox2.Text = "";
        }
        private void PlayThread()
        {
            axWindowsMediaPlayer1.URL = System.Environment.CurrentDirectory + @"\Levitate.mp3";//I:\CloudMusic\胡伟立 - 随缘(粤).mp3
            axWindowsMediaPlayer1.Ctlcontrols.play();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (axWindowsMediaPlayer1.playState != WMPPlayState.wmppsPlaying)
            {
                PlayThread();
            }
            else
            {
                axWindowsMediaPlayer1.Ctlcontrols.stop();
            }
        }

        private void btnSubmitOrder_Click(object sender, EventArgs e)
        {
            SubminOrder();
        }


        private void SubminOrder()
        {
            string token = txttoken.Text;
            var productURL = string.Format("https://api.9yiwu.com/yiwu/product/detail.do?productId=411210&accessToken={0}&mChannal=NG_APP", token);
            var proStr = HttpHelper.HttpPostParams(productURL, null);
            var projson = JObject.Parse(proStr);
            if (projson["code"].ToString() == "0")
            {
                textBox2.Text += "下单商品：" + projson["result"]["name"].ToString() + Environment.NewLine;

                /*------111----------skuId=496272*/
                var queryUrl = string.Format("https://api.9yiwu.com/yiwu/promotion/query?accessToken={0}&mChannal=NG_APP", token);
                string jsonp1 = "{\"orderSkuDTOs\":[{\"skuPrices\":[{\"mobilePhone\":\"18277163317\",\"price\":\"1599.00\",\"skuId\":\"496272\",\"quantity\":1}],\"storeId\":\"JD\"}],\"userMobile\":\"18277163317\"}";
                var queryStr = HttpHelper.HttpPostParams(queryUrl, jsonp1);
                var queryjson = JObject.Parse(queryStr);
                /*------111----------*/
                if (queryjson["code"].ToString() == "0")
                {
                    var calcUrl = string.Format("https://api.9yiwu.com/yiwu/promotion/calculate?accessToken={0}&mChannal=NG_APP", token);
                    string jsonp2 = "{\"orderSkuDTOs\":[{\"skuPrices\":[{\"mobilePhone\":\"18277163317\",\"price\":\"1599.00\",\"skuId\":\"496272\",\"quantity\":1}],\"storeId\":\"JD\"}],\"promotionDTOs\":[]}";
                    var calcStr = HttpHelper.HttpPostParams(calcUrl, jsonp2);
                    var calcjson = JObject.Parse(queryStr);
                    if (calcjson["code"].ToString() == "0")
                    {
                        var submitUrl = string.Format("https://api.9yiwu.com/yiwu/checkout/submit/order/immediately?accessToken={0}&mChannal=NG_APP", token);
                        string jsonp3 = "{\"addressId\":\"201610091246500000\",\"mobilePhone\":\"18277163317\",\"price\":\"1599.00\",\"promotionDTOs\":[],\"quantity\":\"1\",\"skuId\":\"496272\",\"storeId\":\"JD\"}";
                        var submitStr = HttpHelper.HttpPostParams(submitUrl, jsonp3);
                        var submitjson = JObject.Parse(submitStr);
                        if (submitjson["code"].ToString() == "0")
                        {
                            textBox2.Text += "下单成功" + Environment.NewLine;
                        }
                        else
                        {
                            textBox2.Text = submitjson["msg"].ToString() + Environment.NewLine;
                        }
                    }
                }
            }
        }
    }
}
